package com.guanjialhx.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.guanjialhx.config.WeiXinConfig;
import com.guanjialhx.pojo.Rebate;
import com.guanjialhx.pojo.RebateInfo;
import com.guanjialhx.pojo.Teacher;
import com.guanjialhx.pojo.Train;
import com.guanjialhx.utils.MyHttpUtil;
import com.guanjialhx.utils.RedisUtil;
import com.guanjialhx.utils.WeChatUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.Id;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author 邓昕劼
 * @version 1.3
 * <p>
 * 用于日对账    每天去定时查询对应的渠道老师招生情况并付费给渠道老师
 */
@RestController
@RequestMapping(value = "/WeiXinTiming")
public class WeiXinTiming {
    //日志打印
    public static final Logger log = LoggerFactory.getLogger(WeiXinTiming.class);

    //微信转账api
    private static String PATH = "https://api.mch.weixin.qq.com/v3/transfer/batches";     //转账的路径

    //居家照护管家公众号appid
    private String APPID = "wxcb64d81519996b30";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 访问启效云的参数
     */
    private static final String appKey = "d3aa45bbd1e94d70b5fe59b1fa37da21";
    private static final String appSecret = "883fbc209be344e899544af7c7caa0fc";
    private static final String qxUrl = "https://changhu.qixiaocloud.com";


    /**
     * 测试
     */
    @GetMapping("/text")
    public void text() {
        try {


        } catch (Exception e) {
            e.printStackTrace();

        }
    }


    /**
     * 每日根据渠道分配对费用合规的流程发放
     */
//    @Scheduled(cron = "* * * * * *")
    @Scheduled(cron = "0 0 17 * * ?") //每天下午5点扫描今天之前待返费的数据
    @GetMapping("/Daily")
    public void DailyReconciliation() {
        try {
            List<Map> TrainingSituationList = new ArrayList<>();
            List<Map> list = new ArrayList<>();   //【转账明细列表】
            String qxToken = this.token();
            Map<String, String> headMap = new HashMap<>();
            headMap.put("Authorization", qxToken);
            Map param = new HashMap();
            String url = "https://changhu.qixiaocloud.com/open/qx-apaas-lowcode/gj/SelectFanFeiId";
            String FanFeiId = WeChatPayInfoController.postJsonParam(url, param, headMap);
            log.info("FanFeiId：" + FanFeiId);
            net.sf.json.JSONObject FanFeiIdJson = net.sf.json.JSONObject.fromObject(FanFeiId);
            net.sf.json.JSONObject FanFeiData = net.sf.json.JSONObject.fromObject(FanFeiIdJson.getString("data"));
            if (!FanFeiData.isEmpty()) {
                String txtID = FanFeiData.getString("id");
                List<String> txtIDList = Arrays.asList(txtID.split(","));
                List<Rebate> ClassUserList = txtIDList.stream().map((resp) -> {
                    Rebate rebate = new Rebate();
                    // 删除双引号和方括号
                    String result1 = resp.replace("\"", "").replace("[", "").replace("]", "");
                    rebate.setId(result1);
                    return rebate;
                }).collect(Collectors.toList());
                List<CompletableFuture<Rebate>> futures = new ArrayList<>();
                for (Rebate rebate : ClassUserList) {
                    CompletableFuture<Rebate> future = CompletableFuture.supplyAsync(() -> {
                        try {
                            return fetchData(rebate);
                        } catch (Exception e) {
                            // 处理异常
                            e.printStackTrace();
                            return null;
                        }
                        // 并行处理每个 ClassUser 的查询
                    });
                    futures.add(future);
                }
                // 等待所有异步操作完成
                CompletableFuture<Void> allFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]));
                try {
                    allFutures.get(); // 等待所有异步操作完成
                } catch (Exception e) {
                    // 处理异常
                    e.printStackTrace();
                }
                // 获取异步操作的结果
                List<Rebate> RebateListS = futures.stream()
                        .map(CompletableFuture::join) // 获取异步操作的结果
                        .collect(Collectors.toList());
                Map<String, RebateInfo> openidTotalInfoMap = new HashMap<>();
                // 遍历 RebateListS
                for (Rebate rebate : RebateListS) {
                    String openid = rebate.getOpenid();
                    float amoney = Float.parseFloat(rebate.getAmoney());
                    String name = rebate.getName();
                    String ckid = rebate.getCkid();
                    String idCard = rebate.getIdCard();

                    // 检查 openidTotalInfoMap 中是否已经存在该 openid 的信息
                    if (openidTotalInfoMap.containsKey(openid)) {
                        // 如果存在，则更新该 openid 对应的信息
                        RebateInfo info = openidTotalInfoMap.get(openid);
                        info.setTotalAmoney(info.getTotalAmoney() + amoney);
                        // 如果需要更新姓名和身份证信息，可以在这里添加相应的逻辑
                    } else {
                        // 如果不存在，则初始化为当前信息
                        RebateInfo info = new RebateInfo(name, ckid, amoney, idCard);
                        openidTotalInfoMap.put(openid, info);
                    }
                }
                // 打印累加结果
                for (Map.Entry<String, RebateInfo> entry : openidTotalInfoMap.entrySet()) {
                    String openid = entry.getKey();
                    RebateInfo info = entry.getValue();
                    float totalAmoney = info.getTotalAmoney();
                    log.info("entry: " + entry);
                    //转账明细
                    Map<String, Object> map = new HashMap<>();
                    map.put("out_detail_no", UUID.randomUUID().toString().replace("-", "")); //商家明细单号
                    map.put("transfer_amount", totalAmoney);                      //转账金额
//                map.put("user_name",text(teacher.getName()));                //用户姓名
                    // 创建Date对象获取当前日期和时间
                    Date now = new Date();
                    // 创建SimpleDateFormat对象，定义日期和时间格式
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    map.put("transfer_remark", dateFormat.format(now) + "力合新招生返费");  //备注
                    map.put("openid", openid);      //用户openid
                    list.add(map);
                    //获取返费信息的数据
                    Map<String, Object> mapTeacher = new HashMap();
                    mapTeacher.put("name", info.getName());
                    mapTeacher.put("identity", info.getIdCard());
                    mapTeacher.put("idArray", txtIDList);
                    mapTeacher.put("sum", totalAmoney);
                    TrainingSituationList.add(mapTeacher);
                }
            }
            for (Map map : list) {
                log.info("map = " + map);
            }
            /**
             *     微信转账代码
             */
            //筛选【转账明细列表】   使用迭代器遍历列表并删除满足条件的Map
            Iterator<Map> iterator = list.iterator();
            while (iterator.hasNext()) {
                Map<String, Float> map = iterator.next();
                if (map.containsKey("transfer_amount") && map.get("transfer_amount").equals(0.0f)) {
                    iterator.remove(); // 删除当前迭代的元素
                }
            }
            // 转账总金额 和 明细列表
            double totalAmount = 0.0;
            for (Map map : list) {
                if (map.containsKey("transfer_amount")) {
                    totalAmount += (float) map.get("transfer_amount");
                    double transferAmount = (float) map.get("transfer_amount");
                    map.put("transfer_amount", (int) (transferAmount * 100)); // 转换为分的形式
                }
                log.info(map.get("transfer_remark") + "明细列表map = " + map);
            }
            // 转账总金额转换为分的形式
            int totalAmountInCents = (int) (totalAmount * 100);
            log.info("所有老师转账总金额 = " + totalAmountInCents);
            JSONObject object = new JSONObject();
            object.put("appid", APPID);
            object.put("out_batch_no", UUID.randomUUID().toString().replace("-", ""));    //商家批次单号
            object.put("batch_name", "力合新老师招生返费");       //批次名称
            object.put("batch_remark", "力合新老师招生返费");     //批次备注
            object.put("total_amount", totalAmountInCents);          //转账总金额 单位分
            object.put("total_num", list.size());               //转账总笔数
            object.put("transfer_detail_list", list);//【转账明细列表】
            String resStr = MyHttpUtil.postTransBatRequest(
                    PATH,
                    object.toJSONString(),
                    WeiXinConfig.MERCHANT_SERIAL_NUMBER,
                    WeiXinConfig.MERCHANT_ID,
                    WeiXinConfig.MERCHANT_PRIVATE_KEY_PATH);
            log.info("返回消息===" + resStr);
            JsonObject jsonObject = JsonParser.parseString(resStr).getAsJsonObject();
            String batchId = jsonObject.get("batch_id").getAsString();
            String batchStatus = jsonObject.get("batch_status").getAsString();
            String createTime = jsonObject.get("create_time").getAsString();
            String outBatchNo = jsonObject.get("out_batch_no").getAsString();
            log.info("batchId:" + batchId);
            log.info("batchStatus:" + batchStatus);
            log.info("createTime:" + createTime);
            log.info("outBatchNo:" + outBatchNo);
            /**
             *   转账成功之后
             */
            if (!outBatchNo.equals("")) { //转账成功添加返费情况记录
                for (Map map : TrainingSituationList) {
                    log.info("map:" + map);
                    // 从Map中获取"idArray"的值
                    List<String> idArray = (List<String>) map.get("idArray");
                    for (String ID : idArray) { //根据报名的人数循环
                        qxToken = this.token();
                        String urlRebate = "https://changhu.qixiaocloud.com/open/qx-apaas-lowcode/gj/InstallRebateSituation";
                        //判断是否在有效时间里面
                        Map<String, String> headMapRebate = new HashMap<>();
                        Map paramRebatee = new HashMap();
                        headMapRebate.put("Authorization", qxToken);
                        paramRebatee.put("name", map.get("name"));
                        paramRebatee.put("identity", map.get("identity"));
                        Float sum = (Float) map.get("sum");
                        paramRebatee.put("sumMoney", String.valueOf(sum));
                        paramRebatee.put("out_batch_no", outBatchNo);//商户批次号
                        paramRebatee.put("batch_id", batchId); //微信批次号
                        // 解析原始日期时间字符串为OffsetDateTime对象
                        OffsetDateTime offsetDateTime = OffsetDateTime.parse(createTime);
                        // 转换为本地日期时间(LocalDateTime)，即去掉时区信息
                        LocalDateTime localDateTime = offsetDateTime.toLocalDateTime();
                        // 定义日期时间格式化器
                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                        // 格式化本地日期时间为目标格式字符串
                        String formattedDateTimeString = localDateTime.format(formatter);
                        paramRebatee.put("create_time", formattedDateTimeString); //批次创建时间
                        paramRebatee.put("ID", text(ID)); //报名用户ID流水号
                        String qxAdd2 = LoginController.postJsonParam(urlRebate, paramRebatee, headMapRebate);
                        log.info("添加返费情况数据回调= " + qxAdd2);
                    }
                }
            } else { //转账失败就发公众号通知
                log.info("返费失败！");
//                String appId = "wxcb64d81519996b30";
//                String appSecret = "0bd137a776a560c9562692626d559a51";
//                for (Map map : TrainingSituationList) {
//                    String accessToken = String.valueOf(redisUtil.get("WeChat_access_token"));
//                    if (accessToken == null || "null".equals(accessToken)) {
//                        // 将access_token存入redis中 key过期时间 90分钟
//                        accessToken = WeChatUtil.getAccess_token(appId,appSecret);
//                        redisUtil.set("WeChat_access_token", accessToken, 5400);
//                    }
//                    String serverURL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
//                    //最终提交的数据
//                    com.alibaba.fastjson.JSONObject jo = new com.alibaba.fastjson.JSONObject();
//                    //公众号数据
//                    JSONObject data = new JSONObject();
//                    //返费失败时间
//                    JSONObject keyword1 = new JSONObject();
//                    keyword1.put("value", "2024-05-10 16:59:00");
//                    keyword1.put("color", "#29C160");
//                    data.put("keyword1", keyword1);
//                    //返费失败原因
//                    JSONObject keyword2 = new JSONObject();
//                    keyword2.put("value", "返费失败原因");
//                    keyword2.put("color", "#29C160");
//                    data.put("keyword2", keyword2);
//                    jo.put("data", data);
//                    jo.put("touser", "oBHv56uuzqyXqbDOqXv3wcGZC-Z0");  //openid  这里要换成动态的openid
//                    jo.put("template_id", "c7LkFfGnKsa8u89-xaCrxVyyk5mm7Px9nvyMU-48ALQ");
//                    String result1 = WeChatUtil.sendInformationToUsers(serverURL, jo);
//                    if (result1.contains("40001")) {
//                        // 重新获取accessToken
//                        accessToken = WeChatUtil.getAccess_token(appId,appSecret);
//                        redisUtil.set("WeChat_access_token", accessToken, 5400);
//                        serverURL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
//                        WeChatUtil.sendInformationToUsers(serverURL, jo);
//                    }
//                }
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
    }


    /**
     * 管家系统同步力合新系统
     */
    //    @Scheduled(cron = "* * * * * *")
    @Scheduled(cron = "0 0 21 * * ?") //每天晚上21点执行
    @GetMapping("/synchronization")
    public void synchronization() {
        try {
            //判断是否在有效时间里面
            String qxToken = this.token();
            /** 查询管家中未完成的数据**/
            Map<String, String> headMap = new HashMap<>();
            Map param = new HashMap();
            String url = "https://changhu.qixiaocloud.com/open/qx-apaas-lowcode/gj/SelectSTrain";
            headMap.put("Authorization", qxToken);
            String qxAdd = WeChatPayInfoController.postJsonParam(url, param, headMap);
            net.sf.json.JSONObject qxAddJJson = net.sf.json.JSONObject.fromObject(qxAdd);
            net.sf.json.JSONObject data = net.sf.json.JSONObject.fromObject(qxAddJJson.getString("data"));
            log.info("查询管家培训记录信息data = " + data);
            String name = data.getString("name");
            String identity = data.getString("identity");
            String id = data.getString("id");
            List<String> nameList = Arrays.asList(name.split(","));
            List<String> identityList = Arrays.asList(identity.split(","));
            List<String> idList = Arrays.asList(id.split(","));
            List<Train> TrainDataList = new ArrayList<>();
            for (int i = 0; i < Math.min(Math.min(identityList.size(), nameList.size()), idList.size()); i++) {
                Train train = new Train(nameList.get(i), identityList.get(i), idList.get(i));
                TrainDataList.add(train);
                log.info("train = " + train);
            }
            /**循环管家数据同步力合新**/
            for (Train train : TrainDataList) {
                /** 查询管家中未完成的数据**/
                String url2 = "https://changhu.qixiaocloud.com/open/qx-apaas-lowcode/lhx/SelectApply";
                Map param2 = new HashMap();
                param2.put("name", train.getName());
                param2.put("identity", train.getIdentity());
                String qxAdd2 = WeChatPayInfoController.postJsonParam(url2, param2, headMap);
                net.sf.json.JSONObject qxAddJJson2 = net.sf.json.JSONObject.fromObject(qxAdd2);
                net.sf.json.JSONObject data2 = net.sf.json.JSONObject.fromObject(qxAddJJson2.getString("data"));
                log.info("提供管家参数 = " + train);
                log.info("力合新到查询= " + data2);

                /**更新同步力合新数据**/
                Map param3 = new HashMap();
                qxToken = this.token();
                Map<String, String> headMap3 = new HashMap<>();
                String url3 = "https://changhu.qixiaocloud.com/open/qx-apaas-lowcode/gj/Synchronous";
                headMap3.put("Authorization", qxToken);
                /**
                 * 力合新    ClassState  1：报名中  2：已开班  3：鉴定中
                 * 管家系统  同步状态   1：已关联   2：已开班  3：鉴定中
                 * **/
                //has的意思就是如果获取到了值就是true  没有获取到值就是false
                /**一、 这个if判断的是查询到力合新系统中对应的学员的信息还未分班， 已关联**/
                if (data2.has("courseType") && data2.get("ClassType").equals("未分班") && data2.has("id")) {
                    param3.put("id", train.getId());
                    param3.put("name", train.getName());
                    param3.put("identity", train.getIdentity());
                    param3.put("courseType", data2.get("courseType"));
                    param3.put("synchronous", "1");
                    String qxAdd3 = WeChatPayInfoController.postJsonParam(url3, param3, headMap3);
                    log.info("未分班已关联 = " + qxAdd3);
                }
                /** 二、这个if判断的是查询到力合新系统中对应的学员 对应的班级已经报名了， 已关联**/
                if (data2.has("courseType") && data2.get("ClassType").equals("已分班") && data2.has("id")
                        && data2.has("ClassName") && data2.get("ClassState").equals("1")) {
                    param3.put("id", train.getId());
                    param3.put("name", train.getName());
                    param3.put("identity", train.getIdentity());
                    param3.put("courseType", data2.get("courseType"));
                    param3.put("synchronous", "1");
                    String qxAdd3 = WeChatPayInfoController.postJsonParam(url3, param3, headMap3);
                    log.info("已分班未培训已关联 = " + qxAdd3);
                }
                /** 三、这个if判断的是查询到力合新系统中对应的学员 对应的班级已经培训中了， 已开班**/
                if (data2.has("courseType") && data2.get("ClassType").equals("已分班") && data2.has("id")
                        && data2.has("ClassName") && data2.get("ClassState").equals("2")) {
                    param3.put("id", train.getId());
                    param3.put("name", train.getName());
                    param3.put("identity", train.getIdentity());
                    param3.put("courseType", data2.get("courseType"));
                    param3.put("synchronous", "2");
                    param3.put("ClassState", "已开班");
                    param3.put("ClassName", data2.get("ClassName"));
                    String qxAdd3 = WeChatPayInfoController.postJsonParam(url3, param3, headMap3);
                    log.info("班级培训中已分班 = " + qxAdd3);
                }
                /** 四、这个if判断的是查询到力合新系统中对应的学员 对应的班级已经鉴定中了， 已鉴定**/
                if (data2.has("courseType") && data2.get("ClassType").equals("已分班") && data2.has("id")
                        && data2.has("ClassName") && data2.get("ClassState").equals("3")) {
                    param3.put("id", train.getId());
                    param3.put("name", train.getName());
                    param3.put("identity", train.getIdentity());
                    param3.put("courseType", data2.get("courseType"));
                    param3.put("ClassState", "鉴定中");
                    param3.put("synchronous", "3");
                    param3.put("ClassName", data2.get("ClassName"));
                    String qxAdd3 = WeChatPayInfoController.postJsonParam(url3, param3, headMap3);
                    log.info("班级鉴定中 = " + qxAdd3);
                }
                //清空param3
                param3.clear();
                /**未匹配到的人没有courseType信息，所以不会做改变，在培训记录中还是报名中**/
                System.out.println();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    /**
     * 下面是工具方法--------------------------------------------------------------------------------------------------------------
     */

    private Rebate fetchData(Rebate rebate) {
        try {
            String url2 = "https://changhu.qixiaocloud.com/open/qx-apaas-lowcode/gj/SelectByIDRebate";
            //判断是否在有效时间里面
            Map<String, String> headMap2 = new HashMap<>();
            Map param2 = new HashMap();
            String qxToken = this.token();
            headMap2.put("Authorization", qxToken);
            param2.put("id", rebate.getId());
            String qxAdd2 = LoginController.postJsonParam(url2, param2, headMap2);
            net.sf.json.JSONObject qxAddJJson2 = net.sf.json.JSONObject.fromObject(qxAdd2);
            net.sf.json.JSONObject data2 = net.sf.json.JSONObject.fromObject(qxAddJJson2.getString("data"));
            Rebate rebate2 = new Rebate();
            setUserProperties(rebate2, data2);
            return rebate2;
        } catch (Exception e) {
            return null;
        }
    }

    public void setUserProperties(Rebate rebate, net.sf.json.JSONObject data2) {
        rebate.setAmoney(getValue(data2, "amoney"));
        rebate.setCkid(getValue(data2, "ckid"));
        rebate.setName(getValue(data2, "name"));
        rebate.setTime(getValue(data2, "time"));
        rebate.setId(getValue(data2, "id"));
        rebate.setOpenid(getValue(data2, "openid"));
        rebate.setIdCard(getValue(data2, "idCard"));
    }

    private String getValue(net.sf.json.JSONObject data, String key) {
        return data.has(key) ? data.getString(key) : null;
    }


    //判断集合为空使用
    public static <T> List<T> mergeStreams(List<T> firstList, List<T> secondList) {
        // 检查两个列表是否都不为null
        if (firstList != null && secondList != null) {
            // 使用Stream.concat合并两个流
            return Stream.concat(firstList.stream(), secondList.stream())
                    .collect(Collectors.toList()); // 收集到一个新的列表中
        } else if (firstList != null) {
            // 如果只有第一个列表不为null，则只返回第一个列表
            return new ArrayList<>(firstList);
        } else if (secondList != null) {
            // 如果只有第二个列表不为null，则只返回第二个列表
            return new ArrayList<>(secondList);
        } else {
            // 如果两个列表都为null，返回一个空的列表
            return new ArrayList<>();
        }
    }

    public String text(String text) {
        return text.replace("\"", "").replace("[", "").replace("]", "");
    }

    public String DataType(String data) {
        // 创建 SimpleDateFormat 对象来解析输入日期字符串
        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
        inputFormat.setTimeZone(TimeZone.getTimeZone("GMT+8")); // 设置时区以匹配输入字符串的时区
        String outputDateFormat = "yyyy-MM-dd HH:mm:ss";
        // 创建 SimpleDateFormat 对象来格式化输出日期字符串
        SimpleDateFormat outputFormat = new SimpleDateFormat(outputDateFormat);
        outputFormat.setTimeZone(TimeZone.getTimeZone("GMT+8")); // 通常输出格式不需要时区，但这里保持一致
        try {
            // 解析输入日期字符串
            java.util.Date date = inputFormat.parse(data);
            // 格式化日期为所需的输出格式
            return outputFormat.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 生成访问启效云的token
     */
    public String token() {
        try {
            String url = qxUrl + "/open/oauth/token";
            Map<String, String> headMap = new HashMap<>();
            Map param = new HashMap();
            param.put("appKey", appKey);
            param.put("appSecret", appSecret);
            String qxLogin = null;
            qxLogin = WeChatPayInfoController.postJsonParam(url, param, headMap);
            log.info("token获取:" + qxLogin);
            net.sf.json.JSONObject qxLoginJson = net.sf.json.JSONObject.fromObject(qxLogin);
            String success = qxLoginJson.getString("success");
            if ("true".equals(success)) {
                net.sf.json.JSONObject qxData = net.sf.json.JSONObject.fromObject(qxLoginJson.getString("data"));
                String qxToken = qxData.getString("access_token");
                log.info("token:" + qxToken);
                //将token存到redis设置全局有效时间 10分钟
                return qxToken;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将map数据转成json数据
     */
    public static String postJsonParam(String url, Map<String, String> param, Map<String, String> headMap) throws Exception {
        String jsonparam = mapToJSON(param);
        return doPost(url, jsonparam, headMap);
    }

    /**
     * map 转 json
     *
     * @param param
     * @return
     */
    public static String mapToJSON(Map param) {
        String json = JSON.toJSONString(param);
        return json;
    }

    /**
     * post请求（用于请求json格式的参数）
     *
     * @param url
     * @param params
     * @param headMap
     * @return
     */
    public static String doPost(String url, String params, Map<String, String> headMap) throws Exception {

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);// 创建httpPost
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        //如果headMap不为空，则需要添加接口鉴权字段
        if (headMap != null) {
            Iterator it = headMap.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next().toString();
                httpPost.setHeader(key, headMap.get(key));
            }
        }
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity(params, charSet);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity, "UTF-8");
                return jsonString;
            } else {
                System.out.println("!!!!!!!!responseEntity:" + EntityUtils.toString(response.getEntity(), "UTF-8"));
                return "请求失败，服务器状态码：" + state;
            }
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 根据身份证计算出生年月
     */
    public static String getBirthDateFromIDCard(String idCardNumber) {
        // 身份证号码中出生日期的位置
        String birthDatePart = idCardNumber.substring(6, 14);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        try {
            Date birthDate = sdf.parse(birthDatePart);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(birthDate);
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH) + 1;
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            return String.format("%d-%d-%d", year, month, day);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据身份证计算性别
     */
    public static String getGenderFromIDCard(String idCardNumber) {
        // 身份证号码中性别码的位置
        int genderCode = Integer.parseInt(idCardNumber.substring(16, 17));
        if (genderCode % 2 == 0) {
            return "2";
        } else {
            return "1";
        }
    }


}
